package com.ihr360.job.core.listener;

import com.ihr360.job.core.JobExecutionListener;
import com.ihr360.job.core.entity.JobExecution;
import org.springframework.core.Ordered;

import java.util.Iterator;
import java.util.List;

public class CompositeJobExecutionListener implements JobExecutionListener {
    private OrderedComposite<JobExecutionListener> listeners = new OrderedComposite<JobExecutionListener>();

    /**
     * Public setter for the listeners.
     *
     * @param listeners
     */
    public void setListeners(List<? extends JobExecutionListener> listeners) {
        this.listeners.setItems(listeners);
    }

    /**
     * Register additional listener.
     *
     * @param jobExecutionListener
     */
    public void register(JobExecutionListener jobExecutionListener) {
        listeners.add(jobExecutionListener);
    }

    /**
     * Call the registered listeners in reverse order, respecting and
     * prioritising those that implement {@link Ordered}.
     * @see com.ihr360.job.core.JobExecutionListener#afterJob(JobExecution)
     */
    @Override
    public void afterJob(JobExecution jobExecution) {
        for (Iterator<JobExecutionListener> iterator = listeners.reverse(); iterator.hasNext();) {
            JobExecutionListener listener = iterator.next();
            listener.afterJob(jobExecution);
        }
    }

    /**
     * Call the registered listeners in order, respecting and prioritising those
     * that implement {@link Ordered}.
     * @see com.ihr360.job.core.JobExecutionListener#beforeJob(JobExecution)
     */
    @Override
    public void beforeJob(JobExecution jobExecution) {
        for (Iterator<JobExecutionListener> iterator = listeners.iterator(); iterator.hasNext();) {
            JobExecutionListener listener = iterator.next();
            listener.beforeJob(jobExecution);
        }
    }
}